using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text;
using System.Text.Json;
using MVCWeekOne.Models;

namespace MVCWeekOne.Controllers
{
    public class AccountController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ApiSettings _apiSettings;

        public AccountController(IHttpClientFactory httpClientFactory, IOptions<ApiSettings> apiSettings)
        {
            _httpClientFactory = httpClientFactory;
            _apiSettings = apiSettings.Value;
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // 验证验证码 - 暂时跳过验证码验证，因为现在是前端生成
            // var sessionCaptcha = HttpContext.Session.GetString("Captcha");
            // if (string.IsNullOrEmpty(sessionCaptcha) || 
            //     !sessionCaptcha.Equals(model.Captcha, StringComparison.OrdinalIgnoreCase))
            // {
            //     ModelState.AddModelError("Captcha", "验证码错误");
            //     return View(model);
            // }

            try
            {
                var client = _httpClientFactory.CreateClient();
                
                // 根据API定义，登录是GET方法，参数通过Query String传递
                var loginUrl = $"{_apiSettings.ReadApiUrl}/Account/Login?Name={Uri.EscapeDataString(model.Username)}&Pwd={Uri.EscapeDataString(model.Password)}";
                
                var response = await client.GetAsync(loginUrl);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var loginResult = JsonSerializer.Deserialize<ApiResult<AccountLoginDTO>>(result);
                    
                    if (loginResult?.IsSuccess == true && loginResult.Data != null)
                    {
                        // 保存登录信息到Session
                        HttpContext.Session.SetString("Token", loginResult.Data.ToKen);
                        HttpContext.Session.SetString("UserName", loginResult.Data.accMsg.Name);
                        HttpContext.Session.SetString("RealName", loginResult.Data.accMsg.RealName);
                        
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", loginResult?.Msg ?? "登录失败");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "登录失败，请检查用户名和密码");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", $"登录异常: {ex.Message}");
            }

            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> UserManagement()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return RedirectToAction("Login");
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?Index=1&Size=10");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var accountResult = JsonSerializer.Deserialize<ApiPageing<AccountDTO>>(result);
                    
                    if (accountResult != null)
                    {
                        return View(accountResult.Items);
                    }
                }

                return View(new List<AccountDTO>());
            }
            catch
            {
                return View(new List<AccountDTO>());
            }
        }

        /// <summary>
        /// 获取用户分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetUserPage(int page = 1, int limit = 10, string name = "")
        {
            var token = HttpContext.Session.GetString("Token");
            
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { code = 1, msg = "未登录", count = 0, data = new List<AccountDTO>() });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 构建查询参数 - Layui传递的是page和limit，我们需要转换为Index和Size
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(name))
                    queryParams.Add($"Name={Uri.EscapeDataString(name)}");
                
                queryParams.Add($"Index={page}");
                queryParams.Add($"Size={limit}");
                
                var queryString = string.Join("&", queryParams);
                var url = $"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?{queryString}";

                var response = await client.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var accountResult = JsonSerializer.Deserialize<ApiPageing<AccountDTO>>(result);
                    
                    if (accountResult != null)
                    {
                        // 将API返回的数据格式转换为Layui期望的格式
                        // Layui期望: {code: 0, msg: "success", count: total, data: [...]}
                        // API返回: {code: 200, msg: "...", totaCount: ..., pageData: [...]}
                        var responseData = new { 
                            code = accountResult.Code == 200 ? 0 : 1, // 成功时返回0，失败时返回1
                            msg = accountResult.Msg ?? "success", 
                            count = accountResult.TotaCount,
                            data = accountResult.PageData?.ToList() ?? new List<AccountDTO>()
                        };
                        
                        return Json(responseData);
                    }
                }

                return Json(new { code = 1, msg = "获取用户数据失败", count = 0, data = new List<AccountDTO>() });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"获取用户数据异常: {ex.Message}", count = 0, data = new List<AccountDTO>() });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetRoles()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Role/GetRoleAll");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var roleResult = JsonSerializer.Deserialize<ApiResult<List<RoleDto>>>(result);
                    
                    if (roleResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, data = roleResult.Data });
                    }
                }

                return Json(new { success = false, message = "获取角色数据失败" });
            }
            catch
            {
                return Json(new { success = false, message = "获取角色数据失败" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> AddUser([FromBody] dynamic model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 将dynamic转换为JsonElement来正确访问属性
                var jsonElement = (JsonElement)model;
                
                // 验证必需字段
                if (!jsonElement.TryGetProperty("name", out var nameElement) || 
                    !jsonElement.TryGetProperty("pwd", out var pwdElement) || 
                    !jsonElement.TryGetProperty("realName", out var realNameElement) || 
                    !jsonElement.TryGetProperty("roleId", out var roleIdElement))
                {
                    return Json(new { success = false, message = "请填写完整信息" });
                }

                var name = nameElement.GetString();
                var pwd = pwdElement.GetString();
                var realName = realNameElement.GetString();

                // 验证字段不为空
                if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(pwd) || string.IsNullOrWhiteSpace(realName))
                {
                    return Json(new { success = false, message = "请填写完整信息" });
                }

                // 处理roleId数组，确保正确处理long类型
                var roleIds = new List<long>();
                if (roleIdElement.ValueKind == JsonValueKind.Array)
                {
                    foreach (var roleId in roleIdElement.EnumerateArray())
                    {
                        if (roleId.ValueKind == JsonValueKind.Number)
                        {
                            roleIds.Add(roleId.GetInt64());
                        }
                    }
                }

                if (roleIds.Count == 0)
                {
                    return Json(new { success = false, message = "请选择角色" });
                }

                var userData = new
                {
                    name = name,
                    pwd = pwd,
                    realName = realName,
                    roleId = roleIds.ToArray()
                };

                var json = JsonSerializer.Serialize(userData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var apiUrl = $"{_apiSettings.WriteApiUrl}/Account/AddAccount";
                var response = await client.PostAsync(apiUrl, content);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var addResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (addResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "用户添加成功！" });
                    }
                    else
                    {
                        return Json(new { success = false, message = addResult?.Msg ?? "添加失败，请检查输入信息" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return Json(new { success = false, message = $"API调用失败: {response.StatusCode} - {errorContent}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"添加失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> DeleteUser(long userId)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.DeleteAsync($"{_apiSettings.WriteApiUrl}/Account/DeleteAccount?AccountId={userId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var deleteResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (deleteResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "用户删除成功！" });
                    }
                    else
                    {
                        return Json(new { success = false, message = deleteResult?.Msg ?? "删除失败" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return Json(new { success = false, message = $"删除失败: {response.StatusCode} - {errorContent}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败: {ex.Message}" });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetUserById(long userId)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 通过分页接口获取用户信息，然后筛选出指定用户
                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?Index=1&Size=1000");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var accountResult = JsonSerializer.Deserialize<ApiPageing<AccountDTO>>(result);
                    
                    if (accountResult?.PageData != null)
                    {
                        // 使用long类型进行ID匹配，支持大数字ID
                        var user = accountResult.PageData.FirstOrDefault(u => u.Id == userId);
                        
                        if (user != null)
                        {
                            return Json(new { success = true, data = user });
                        }
                        else
                        {
                            // 调试信息：记录所有用户的ID
                            var allUserIds = accountResult.PageData.Select(u => u.Id).ToList();
                            return Json(new { success = false, message = $"用户不存在。查找的ID: {userId}, 所有用户ID: {string.Join(", ", allUserIds)}" });
                        }
                    }
                }

                return Json(new { success = false, message = "用户不存在" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取用户信息失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> UpdateUser([FromBody] dynamic model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 将dynamic转换为JsonElement来正确访问属性
                var jsonElement = (JsonElement)model;
                
                // 验证必需字段
                if (!jsonElement.TryGetProperty("accountId", out var accountIdElement) ||
                    !jsonElement.TryGetProperty("name", out var nameElement) || 
                    !jsonElement.TryGetProperty("pwd", out var pwdElement) || 
                    !jsonElement.TryGetProperty("realName", out var realNameElement) || 
                    !jsonElement.TryGetProperty("roleId", out var roleIdElement))
                {
                    return Json(new { success = false, message = "请填写完整信息" });
                }

                var accountId = accountIdElement.GetInt64();
                var name = nameElement.GetString();
                var pwd = pwdElement.GetString();
                var realName = realNameElement.GetString();

                // 验证字段不为空
                if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(pwd) || string.IsNullOrWhiteSpace(realName))
                {
                    return Json(new { success = false, message = "请填写完整信息" });
                }

                // 处理roleId数组，确保正确处理long类型
                var roleIds = new List<long>();
                if (roleIdElement.ValueKind == JsonValueKind.Array)
                {
                    foreach (var roleId in roleIdElement.EnumerateArray())
                    {
                        if (roleId.ValueKind == JsonValueKind.Number)
                        {
                            roleIds.Add(roleId.GetInt64());
                        }
                    }
                }

                if (roleIds.Count == 0)
                {
                    return Json(new { success = false, message = "请选择角色" });
                }

                var userData = new
                {
                    AccountId = accountId,
                    Name = name,
                    Pwd = pwd,
                    RealName = realName,
                    RoleId = roleIds
                };

                var json = JsonSerializer.Serialize(userData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var apiUrl = $"{_apiSettings.WriteApiUrl}/Account/UpdateAccount";
                var response = await client.PutAsync(apiUrl, content);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var updateResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (updateResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "用户更新成功！" });
                    }
                    else
                    {
                        return Json(new { success = false, message = updateResult?.Msg ?? "更新失败，请检查输入信息" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return Json(new { success = false, message = $"API调用失败: {response.StatusCode} - {errorContent}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"更新失败: {ex.Message}" });
            }
        }

        [HttpGet]
        public IActionResult Test()
        {
            return Content("路由测试成功");
        }

        [HttpGet]
        public async Task<IActionResult> TestApi()
        {
            try
            {
                var client = _httpClientFactory.CreateClient();
                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?Index=1&Size=10");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    return Content($"API测试成功: {result}");
                }
                else
                {
                    return Content($"API测试失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                return Content($"API测试异常: {ex.Message}");
            }
        }

        [HttpGet]
        public async Task<IActionResult> TestApiConnection()
        {
            try
            {
                var client = _httpClientFactory.CreateClient();
                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?Index=1&Size=10");
                
                var result = new
                {
                    ApiUrl = $"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?Index=1&Size=10",
                    StatusCode = (int)response.StatusCode,
                    IsSuccess = response.IsSuccessStatusCode,
                    Content = await response.Content.ReadAsStringAsync()
                };
                
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    ApiUrl = $"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?Index=1&Size=10",
                    StatusCode = 0,
                    IsSuccess = false,
                    Error = ex.Message
                });
            }
        }


    }
}
